//@author A0096566M
#include "FileInterface.h"
#include "logger.hpp"

void FileInterface::setRecords(Records& rec){
	taskList = &rec;
}

void FileInterface::setFileName(string newFileName){
	fileName = newFileName;
	log(LOG_DEBUG) << "FileInterface::setFileName - File name set to: " << getFileName();
}

string FileInterface::getFileName(){
	return fileName;
}

int FileInterface::readFile(){
	log(LOG_DEBUG) << "FileInterface::readFile - Reading from file: " << getFileName();
	bool invalidTask = false;
	file.open(this->fileName.c_str(),std::fstream::in);
	if(file.is_open())
	{
		Records rec;
		char *buffer = new char[1000];
		while(!file.eof()){
			file.getline(buffer,1000,'\n');
			string b = buffer;
			if(b != ""){
				Task* t = new Task(b);
				if ((*t).isValid()) {
					rec.addData(*t);
				} else {
					invalidTask = true;
				}
			}
		}

		(*(this->taskList)) = rec;

		file.close();
		delete buffer;
		log(LOG_DEBUG) << "FileInterface::readFile - Done Reading from file: " << getFileName();
		return invalidTask;
	}else{
		log(LOG_DEBUG) << "FileInterface::readFile - Error Reading from file: " << getFileName() << " - (file not open)";
		return -1;
	}
}

int FileInterface::writeFile(){
	log(LOG_DEBUG) << "FileInterface::writeFile - Writing to file: " << getFileName();
	clearFile();
	file.open(this->fileName.c_str(),std::fstream::out|std::fstream::trunc);
	if(file.is_open())
	{
		for(int i=0 ; i<taskList->getRecordSize() ; i++){
			file << taskList->getData(i).toFileString() << "\n";
		}
		file.close();
		log(LOG_DEBUG) << "FileInterface::writeFile - Done Writing to file: " << getFileName();
		return 0;
	}else{
		log(LOG_DEBUG) << "FileInterface::writeFile - Error Writing to file: " << getFileName() << " - (file not open)";
		return -1;
	}
}

int FileInterface::clearFile(){
	file.open(this->fileName.c_str(),std::fstream::out|std::fstream::trunc);
	if(file.is_open())
	{
		file.close();
		return 0;
	}else{
		return -1;
	}
}